package com.itheima.wallet.web.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.itheima.wallet.api.AccountService;
import com.itheima.wallet.api.TradeService;
import com.itheima.wallet.common.domain.Account;
import com.itheima.wallet.common.domain.Trade;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class WalletService {

    @Reference
    private AccountService accountService;

    @Reference
    private TradeService tradeService;

    public Account saveMoney(Double money, String token) {
        //参数校验
        if (money.isNaN() || money <= 0 || StringUtils.isBlank(token)) {
            return null;
        }
        Account account = accountService.queryAccount(token);
        if (account == null) {
            //token校验不通过
            return null;
        }

        //向账户充钱
        Boolean addBalanceBool = accountService.addBalance(account, money);
        //先设定存储账单为‘错误’
        Boolean addTradeBool = false;
        if (addBalanceBool) {
            //雪花算法生成账单ID
            Snowflake snowflake = IdUtil.getSnowflake(1, 1);
            String tread_id = snowflake.nextIdStr();
            //封装账单
            Trade trade = Trade.builder()
                    .trade_id(tread_id)
                    .trade_money(money)
                    .account_id(account.getAccount_id())
                    // ”1“ 为充值
                    .trade_type(1)
                    .build();

            //保存账单
            addTradeBool = tradeService.insertTrade(trade);
        } else {
            //加钱失败
            throw new RuntimeException("加钱失败");
        }

        if (addTradeBool) {
            //成功保存账单
            account.setBalance(account.getBalance() + money);
            return account;
        } else {
            //保存账单失败，回滚加钱操作
            accountService.reduceBalance(account, money);
            throw new RuntimeException("加钱失败");
        }
    }

    /**
     * 取钱、支付
     * @param money
     * @param token
     * @param type
     * @return
     */
    public Account withdrawMoney(Double money, String token, Integer type) {
        //参数校验
        if (money.isNaN() || money <= 0 || StringUtils.isBlank(token)) {
            return null;
        }
        Account account = accountService.queryAccount(token);
        if (account == null) {
            //token校验不通过
            return null;
        }
        if (account.getBalance() < money) {
            //如果支付金额大于余额
            return null;
        }

        //向账户减钱
        Boolean addBalanceBool = accountService.reduceBalance(account, money);

        //先设定存储账单为‘错误’
        Boolean addTradeBool = false;
        if (addBalanceBool) {
            //雪花算法生成账单ID
            Snowflake snowflake = IdUtil.getSnowflake(1, 1);
            String tread_id = snowflake.nextIdStr();
            //封装账单
            Trade trade = Trade.builder()
                    .trade_id(tread_id)
                    //金额为负
                    .trade_money(-money)
                    .account_id(account.getAccount_id())
                    // ”1“ 为充值
                    .trade_type(type)
                    .build();

            //保存账单
            addTradeBool = tradeService.insertTrade(trade);
        } else {
            //减钱失败
            throw new RuntimeException("减钱失败");
        }

        if (addTradeBool) {
            //成功保存账单
            account.setBalance(account.getBalance() - money);
            return account;
        } else {
            //保存账单失败，回滚加钱操作
            accountService.addBalance(account, money);
            throw new RuntimeException("减钱失败");
        }
    }

    public List<Trade> queryTradeList(Integer page, Integer pageSize, String token) {
        //参数校验
        if (page == null || page < 0) {
            page = 1;
        }
        if (pageSize == null || pageSize < 0 || pageSize > 100) {
            pageSize = 10;
        }
        //Token校验
        Account account = accountService.queryAccount(token);
        if (account == null) {
            //token校验不通过
            return null;
        }

        List<Trade> tradeList = tradeService.queryTradeList(page, pageSize, account.getAccount_id());
        if (tradeList == null) {
            //用户没有交易记录
            tradeList = Collections.emptyList();
        }
        return tradeList;
    }
}
